package com.offcn.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.offcn.bean.Role;
import com.offcn.bean.User;
import com.offcn.bean.UserExample;
import com.offcn.mapper.EvaluateMapper;
import com.offcn.mapper.RoleMapper;
import com.offcn.mapper.UserMapper;
import com.offcn.service.UserService;
import com.offcn.utils.OAResult;
import com.offcn.utils.PageView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;

    public PageView<User> getAllUsers(int currentPage,Integer pageSize,String uname) {
        PageHelper.startPage(currentPage,pageSize);
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        if (uname!=null && !uname.equals("")){
            criteria.andUnameLike("%"+uname+"%");
        }
        List<User> userList = userMapper.selectByExample(userExample);
        PageInfo<User> pageInfo=new PageInfo<User>(userList);
        PageView<User> pageView = new PageView<User>(currentPage, pageSize);
        pageView.setTotalrecords(pageInfo.getTotal());
        pageView.setRecords(pageInfo.getList());

        return pageView;
    }

    public OAResult deleteUser(int uid) {
        int rows = userMapper.deleteByPrimaryKey(uid);
        if (rows==1){
            return OAResult.ok(200,"操作成功");
        }
        return OAResult.ok(400,"操作失败");
    }

    public OAResult getUserByUnameAndUpass(String uname, String upass) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUnameEqualTo(uname);
        criteria.andUpassEqualTo(upass);
        List<User> userList = userMapper.selectByExample(userExample);
        if (userList!=null&&userList.size()>0){
            return OAResult.build(200,"登录成功",userList.get(0));
        }
        return OAResult.ok(400,"登录失败");
    }

    public User getUserDetailById(int uid) {
        User user = userMapper.selectByPrimaryKey(uid);
        Role role = roleMapper.selectByPrimaryKey(user.getUtype());
        user.setRole(role);
        return user;
    }
}
